<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>拖拽</title>
		<style type="text/css">
			.backtop{
				display: inline-block;
				position: fixed;
				right: 20px;
				bottom: 20px;
				width: 50px;
				height: 50px;
				background: rgba(0, 0, 0, .6);
				border-radius: 50%;
				text-align: center;
				line-height: 50px;
				color: #fff;
				font-size: 30px;
				-webkit-tap-highlight-color: transparent;
			}
		</style>
	</head>
	<body>
		<a href="#" id="backtop" class="backtop">&uarr;</a>
		<script type="text/javascript">
			var backtop = document.getElementById("backtop");
			drag(backtop, {
				x: true, // x轴允许拖动
				y: true, // y轴允许拖动
			})
			function drag(el, options){
				options.x = typeof options.x !== 'undefined' ? options.x : true;
				options.y = typeof options.y !== 'undefined' ? options.y : false;
				
				if (!options.x && !options.y) return;
				
				var curPoint = {
					x: 0,
					y: 0
				};
				var startPoint = {}; // 手指头刚按下的焦点
				var isTouchMove = false;
				
				el.addEventListener('touchstart', handleStart, false);
				el.addEventListener('touchmove', handleMove, false);
				el.addEventListener('touchend', handleEnd, false);
				
				function handleStart(e) {
					var touch = e.changedTouches[0];
					
					startPoint.x = touch.pageX;
					startPoint.y = touch.pageY;
				}
				function handleMove(e) {
					e.preventDefault(); // 如果有滚动条，则会滚动条滚动，球不动，加上这句解决问题
					
					isTouchMove = true;
					
					var touch = e.changedTouches[0];
					
					var diffPoint = {};
					var movePoint = {
						x: 0,
						y: 0
					}
					
					diffPoint.x = touch.pageX - startPoint.x;
					diffPoint.y = touch.pageY - startPoint.y;
					
					if (options.x) {
						movePoint.x = diffPoint.x + curPoint.x;
					}
					if (options.y) {
						movePoint.y = diffPoint.y + curPoint.y;
					}
					
					move(el, movePoint.x, movePoint.y);
				}
				function handleEnd(e) {
					if (!isTouchMove) return;
					
					var touch = e.changedTouches[0];
					
					curPoint.x += touch.pageX - startPoint.x;
					curPoint.y += touch.pageY - startPoint.y;
					
					isTouchMove = false;
				}
				function move(el, x, y) {
					x = x || 0;
					y = y || 0;
					el.style.transform = 'translate3d(' + x + 'px,' + y +'px, 0)';
				}
			}
		</script>
	</body>
</html>
